<?php

declare(strict_types=1);

namespace App\Command;

use Grpc\ChannelCredentials;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Iat\IatClient;
use Iat\IatRequest;
use Psr\Container\ContainerInterface;

/**
 * @Command
 */
#[Command]
class AsrCommand extends HyperfCommand
{

    protected $name = 'app:asr';

    /**
     * @var ContainerInterface
     */
    protected $container;

    public $stream = '';

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
//        $this->stream = file_get_contents('/var/www/aiad-asr/asr.wav');
        parent::__construct('app:asr');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('Hyperf Demo Command');
    }

    public function handle()
    {
        $asr = config('asr.asr');
        $client = new IatClient($asr['server'], ['credentials' => ChannelCredentials::createInsecure()]);

        $unaryCall = $client->createRec();
        $request = new IatRequest();
        $request->setSessionParam($asr['session_param']);
        $unaryCall->push($request);

        while ($chunk = $this->slice()) {
            $request = new IatRequest();
            $request->setSamples($chunk);
            $unaryCall->push($request);
            usleep(40*1000);
        }

        $request = new IatRequest();
        $request->setEndFlag(true);
        $unaryCall->push($request);
        $unaryCall->end();

        //开始读取数据
        $results = [];
        while ($buffer = $unaryCall->recv()) {
            $data = $buffer;
            $results[] = $data;
            if (($data['ls'] ?? false)) {  //ls值为true时，结束读取,上一次数据为真正结果
                break;
            } else {
                $results[] = $data;
            }
        }
    }

    /**
     * 切割值为1280效果最好
     * @param int $length
     * @return false|string
     */
    public function slice(int $length = 1280 * 4)
    {
        if ($this->stream) {
            $chunk = substr($this->stream, 0, $length);
            $this->stream = substr($this->stream, $length);
            return $chunk;
        }
        return false;
    }
}
